﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace gui {
    /// <summary>
    /// Interaction logic for ConnectBox.xaml
    /// This box is presented to the user to connect to a remote MySQL databse
    /// </summary>
    public partial class ConnectBox : Window {
        public ConnectBox() {
            InitializeComponent();

            // Default Connection Details
            dbURL.Text = "mysql5.dcs.warwick.ac.uk";
            dbPort.Text = "3389";
            dbName.Text = "snag";
            dbUsername.Text = "snag_read";
            dbPassword.Password = "JeBngXFmMQFMheBD";

            // Register Connection Listeners
            NetworkModelConnect.OnConnectedEvent += CloseConnectBox;
            NetworkModelConnect.OnErrorEvent += CloseConnectBox;

            // Make this window the topmost window
            this.Topmost = true;
        }

        private void Connect(object sender, RoutedEventArgs e) {
            int port;
            bool isNum = (int.TryParse(dbPort.Text, out port) && (dbPort.Text.Length < 6));
            if (isNum) {

                // Create new loading box
                LoadingBox lb = new LoadingBox("Attempting to connect to the specified MySQL Database");
                lb.Show();

                // Connect to DB
                ConnectArgs cArgs = new ConnectArgs(dbURL.Text, port, dbName.Text, dbUsername.Text, dbPassword.Password);
                NetworkModelConnect.Instance.ConnectToDataBase(cArgs);
            }
            else {
                MessageBox.Show("Warning : Please enter a valid port number", "Invalid Port Number", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void CloseConnectBox() {
            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate() {
                this.Close();
            }));
        }

        private void Cancel(object sender, RoutedEventArgs e) {
            this.Close();
        }
    }
}
